package com.liebaut.services;

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRPdfExporterParameter;
import net.sf.jasperreports.engine.util.JRSaver;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.sql.SQLException;
import java.util.Locale;
import java.util.Map;

/**
 * Created by Dirk on 14/02/14.
 */
@Service
public class JasperReportWriter {

    @Autowired
    BasicDataSource dataSource;

    public byte[] getPDFReport(String reportFile, Map<String, Object> reportParameters){
        ByteArrayOutputStream output = null;

        InputStream resourceAsStream = null;
        try {
            Locale locale = new Locale("nl", "BE");
            reportParameters.put(JRParameter.REPORT_LOCALE, locale);
            resourceAsStream = new FileInputStream(new File(reportFile));
            JasperDesign jasperDesign = JRXmlLoader.load(resourceAsStream);
            JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
            output = new ByteArrayOutputStream();
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, reportParameters, dataSource.getConnection());
            JRPdfExporter pdfExporter = new JRPdfExporter();
            pdfExporter.setParameter(JRPdfExporterParameter.JASPER_PRINT, jasperPrint);
            pdfExporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM, output);
            pdfExporter.exportReport();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (JRException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return output.toByteArray();
    }
}
